package gbench.appdemo.crawler;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import gbench.common.tree.LittleTree.IRecord;

/**
 * 
 * @author gbench
 *
 * @param <SELF> 子类的实际类型
 */
public class AbstractState <SELF>{
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public boolean stateOfBoolean(String name) {
        return this.state.get().bool(name);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public int stateOfInteger(String name) {
        return this.state.get().i4(name);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public double stateOfDouble(String name) {
        return this.state.get().dbl(name);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public long stateOfLong(String name) {
        return this.state.get().lng(name);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public <T> T stateOfT(String name,Class<T>clazz) {
        return this.state.get().get(name,clazz);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    public String stateOfString(String name) {
        return this.state.get().str(name);
    }
    
    /**
     * 
     * @param <T> 返回值类型
     * @param defaultValue 默认值 或者 值类型
     * @param strings 键名序列
     * @return 属性的值
     */
    @SuppressWarnings("unchecked")
    public <T> T getState(final T defaultValue,final Object ...fields ) {
        final String key = Arrays.stream(fields).map(e->e+"").collect(Collectors.joining("."));
        final Class<T> tclass = defaultValue instanceof Class
            ? (Class<T>)defaultValue
            : defaultValue==null?(Class<T>)Object.class:(Class<T>)defaultValue.getClass();
        final T t = this.stateOfT(key, tclass);
        if(t !=null) 
            return t;
        else
            return defaultValue instanceof Class ? null:defaultValue;
    }
    
    /**
     * 
     * @param <T>
     * @param value
     * @param strings
     * @return
     */
    public <T> SELF setState(T value,String ...strings ) {
        final String key = Arrays.stream(strings).collect(Collectors.joining("."));
        return this.state(key, value);
    }
    
    /**
     * bool 类型的状态
     * @param name
     * @return
     */
    @SuppressWarnings("unchecked")
    public SELF state(final String name, final Object value) {
        
        // 重新设置新的状态信息
        this.state.set(this.state.get().derive(name,value));
        return (SELF)this;
    }

    
    protected AtomicReference<IRecord> state = new AtomicReference<IRecord>(); // 系统状态

}
